package com.leyou.item.web;

import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.entity.SpecParam;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/spec")
public class SpecController {

    @Autowired
    private SpecGroupService groupService;

    @Autowired
    private SpecParamService paramService;

    // 根据商品分类id，查询规格组的集合
    @GetMapping("/groups/of/category")
    public ResponseEntity<List<SpecGroupDTO>> querySpecByCategoryId(@RequestParam("id") Long id) {
        return ResponseEntity.ok(SpecGroupDTO.convertEntityList(groupService.query().eq("category_id", id).list()));
    }

    // 根据分类id查询规格组及组内参数
    @GetMapping("/list")
    public ResponseEntity<List<SpecGroupDTO>> querySpecGroupByCategoryId(@RequestParam("id") Long id) {
        return ResponseEntity.ok(groupService.querySpecGroupByCategoryId(id));
    }

    // 根据条件查询规格参数集合
    @GetMapping("/params")
    public ResponseEntity<List<SpecParamDTO>> querySpecParam(
            @RequestParam(value = "categoryId", required = false) Long categoryId,
            @RequestParam(value = "groupId", required = false) Long groupId,
            @RequestParam(value = "searching", required = false) Boolean searching) {
        return ResponseEntity.ok(paramService.querySpecParam(categoryId, groupId, searching));
    }

    // 新增规格组
    @PostMapping("/group")
    public ResponseEntity<Void> addSpecGroup(@RequestBody SpecGroupDTO specGroupDTO) {
        groupService.save(specGroupDTO.toEntity(SpecGroup.class));
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    // 修改规格组
    @PutMapping("/group")
    public ResponseEntity<Void> updateSpecGroup(@RequestBody SpecGroupDTO specGroupDTO) {
        groupService.updateById(specGroupDTO.toEntity(SpecGroup.class));
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    // 新增规格参数
    @PostMapping("/param")
    public ResponseEntity<Void> addSpecParam(@RequestBody SpecParamDTO specParamDTO) {
        paramService.save(specParamDTO.toEntity(SpecParam.class));
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    // 修改规格参数
    @PutMapping("/param")
    public ResponseEntity<Void> updateSpecParam(@RequestBody SpecParamDTO specParamDTO) {
        paramService.updateById(specParamDTO.toEntity(SpecParam.class));
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

}
